package cn.taketoday.live.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import cn.taketoday.live.BiliBiliApplication;

/**
 * @author TODAY 2021/5/20 0:26
 */
public abstract class FileUtils {
  static String path;

  static {
    ApplicationHome home = new ApplicationHome(BiliBiliApplication.class);
    File jarFile = home.getSource();
    path = URLDecoder.decode(jarFile.getParentFile().toString(), StandardCharsets.UTF_8);
  }

  /**
   * 生成.json格式文件
   */
  public static boolean createJsonFile(String jsonString) throws IOException {
    String path = getApplicationPath();
    path = path + "/set/";
    // 保证创建一个新文件
    File file = new File(path + "set" + ".json");
    file.setWritable(true, false);
    if (!file.exists())
      file.mkdirs();
    if (file.exists()) { // 如果已存在,删除旧文件
      file.delete();
    }
    file.createNewFile();

    // 格式化json字符串
    JSONObject jsonObject = JSONObject.parseObject(jsonString);
    String content = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                                       SerializerFeature.WriteDateUseDateFormat);
    // 生成json格式文件
    try (Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
      // 将格式化后的字符串写入文件
      write.write(content);
      write.flush();
    }
    // 返回是否成功的标记
    return true;
  }

  public static String getApplicationPath() {
    return path;
  }
}
